<?php

namespace App\Http\Middleware;

use App\Models\AdminGroup;
use App\Models\AdminMenu;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;

class AdminAuth
{
    private $user       = null;
    private $adminGroup;
    private $menu       = array();
    private $auth;
    private $action;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
        $this->user = Auth::user();
        $this->adminGroup = AdminGroup::all()->keyBy('id');
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest(action('Admin\AuthController@getLogin'));
            }
        }else{
            if ($this->verify($request))
            {
                //return ShowMsg('error','你没有权限访问此页面！','');
                return view('errors.404');
            }else{
                return $next($request);
            }
        }
    }

    /**
     * 验证管理员权限
     *
     * @return boole
     */
    private function verify($request)
    {
        //没有此用户
        if (empty($this->user))
            return true;
        if ($this->user->type != 'system')
            return true;

        if ($this->getMenu())
        {
            //获取当前ACTION
            $this->action = $request->route()->getActionName();
            $this->action = str_replace('App\Http\Controllers\\','',$this->action);
            //当前ACTION的其他方式
            $a = strstr($this->action, 'get') ? 'get' : 'post';
            $otherAction = str_replace($a,($a == 'get' ? 'post' : 'get'),$this->action);
            //检测是否有权限访问当前目录
            $verifyController = array_where($this->menu, function($key, $v) use($otherAction)
            {
                return $v->controller == $this->action || $v->controller == $otherAction;
            });
            if (empty($verifyController))
                return true;
            //定位当前目录
            foreach ($this->menu as $v)
            {
                if ($this->action == $v->controller)
                {
                    //检测是否有权限访问当前目录

                    //当前目录字体加粗设置
                    $this->menu[$v->id]->bold = 1;
                    $this->getActive($v->id);
                }
            }
            $request->menu  = $this->menu;       //加入到request
            $request->group = $this->adminGroup;
            $request->user  = $this->user;
            return false;
        }
        return true;
    }

    /**
     * 获取目录
     * @param $thisAction
     * @return bool
     */
    private function getMenu()
    {
        if ($this->user->groupID == 1)
        {
            $this->menu = AdminMenu::orderBy('listOrder', 'ASC')->get()->keyBy('id');

        }else{
            //获取目录权限
            $auth = isset($this->adminGroup[$this->user->groupID]) ? $this->adminGroup[$this->user->groupID] : null;
            if (empty($auth))
                return false;

            //获取有权限的目录
            $permissions = explode(',', $auth->permissions);
            $this->menu = AdminMenu::whereIn('id',$permissions)->orderBy('listOrder', 'ASC')->get()->keyBy('id');
        }

        return true;
    }

    /**
     * 获取Active相应目录
     * @param $id
     * @param $menu
     */
    private function getActive($id)
    {
        //当前目录加入Active
        $this->menu[$id]->active = 1;
        //上级目录加入Active
        if($this->menu[$id]->parentID != 0)
        {
            $this->menu[$this->menu[$id]->parentID]->active = 1;
            $this->getActive($this->menu[$id]->parentID);
        }
    }
}
